import React, { useState, useEffect, useRef } from 'react';
import {useNavigate} from 'react-router-dom'
import { LeftOutlined } from '@ant-design/icons';

const Danmaku = ({ messages }) => {
    const navigate = useNavigate()
    // 存储可见的弹幕消息
    const [visibleMessages, setVisibleMessages] = useState([]);
    // 存储当前可使用的消息列表，用于循环播放
    const [currentMessages, setCurrentMessages] = useState([...messages]);
    const containerRef = useRef(null);
    const danmakuRefs = useRef([]);

    // 定时添加新弹幕
    useEffect(() => {
        const interval = setInterval(() => {
            if (currentMessages.length > 0) {
                // 从当前消息列表中取出第一条消息
                const newMessage = currentMessages[0];
                const newCurrentMessages = currentMessages.slice(1);
                // 更新当前消息列表
                setCurrentMessages(newCurrentMessages);
                // 添加新的弹幕到可见列表
                setVisibleMessages((prev) => [
                    ...prev,
                    { id: Date.now(), text: newMessage, top: Math.random() * 80 },
                ]);
            } else {
                // 当消息列表为空时，重新复制一份原始消息列表，实现循环播放
                setCurrentMessages([...messages]);
            }
        }, 1000); // 每隔 1 秒添加一条新弹幕

        return () => clearInterval(interval); // 清除定时器
    }, [messages, currentMessages]);

    // 当弹幕滚动出容器时，重置其位置
    useEffect(() => {
        const checkAndResetDanmaku = () => {
            danmakuRefs.current.forEach((danmaku, index) => {
                if (danmaku) {
                    const rect = danmaku.getBoundingClientRect();
                    if (rect.right < 0) {
                        // 当弹幕完全滚出屏幕左侧时，重置其位置到屏幕右侧
                        danmaku.style.left = '100%';
                        danmaku.style.animation = `moveDanmaku ${Math.random() * 5 + 5}s linear`;
                    }
                }
            });
        };

        // 每 100 毫秒检查一次弹幕位置
        const intervalId = setInterval(checkAndResetDanmaku, 100);
        return () => clearInterval(intervalId);
    }, [visibleMessages]);

    // 监听动画结束事件，移除不可见弹幕
    useEffect(() => {
        const handleAnimationEnd = (e) => {
            setVisibleMessages((prev) => prev.filter((message) => message.id.toString()!== e.target.dataset.id));
        };

        const container = containerRef.current;
        if (container) {
            container.addEventListener('animationend', handleAnimationEnd);
        }

        return () => {
            if (container) {
                container.removeEventListener('animationend', handleAnimationEnd);
            }
        };
    }, []);

    return (
        <div className="danmaku-container" ref={containerRef}>
            <p onClick={()=>navigate(-1)}><LeftOutlined /></p>
            {/* <div className='kan'>3D看房</div> */}
            <div className='kan' onClick={()=>navigate('/three')}>3D看房</div>
            {visibleMessages.map((message, index) => (
                <div
                    key={message.id}
                    className="danmaku"
                    ref={(el) => (danmakuRefs.current[index] = el)}
                    style={{
                        position: 'absolute',
                        top: `${message.top}%`,
                        left: '100%',
                        animation: `moveDanmaku ${Math.random() * 5 + 5}s linear`
                    }}
                    data-id={message.id}
                >
                    {message.text}
                </div>
            ))}
            <style>{`
            .kan{
                width: 6rem;
                height: 2rem;
                color:white;
                border:white 1px solid;
                position: fixed;
                right:1rem;
                top:7rem;
            }
              .danmaku-container {
                    position: relative;
                    width: 100%;
                    height: 10rem;
                    border: 1px solid #ccc;
                    overflow: hidden;
                    background-image:url('./img/bei.webp');
                }
              .danmaku {
                    white-space: nowrap;
                }
              @keyframes moveDanmaku {
                    from {
                        left: 100%;
                    }
                    to {
                        left: -100%;
                    }
                }
            `}</style>
        </div>
    );
};

export default Danmaku;